﻿using CarAppDomain.CarParts.Entities;
using CarAppDomain.CarType.Entities;
using CarAppDomain.CarType.IRepository;
using CarAppDto.CarType.CarTypeVersionDtos;
using CarAppDto.CarType.VehicleSeriesDtos;
using D.UtilSqlsugarOrm;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarAppDomain.CarType.Repository
{
    public class CarTypeVersionEntityRepository : BaseRepository<CarTypeVersionEntity>, ICarTypeVersionEntityRepository
    {
        private readonly ISqlSugarClient sqlSugarClient;
        public CarTypeVersionEntityRepository(ISqlSugarClient db) : base(db)
        {
            sqlSugarClient = db;
        }

        public async Task<int> AddCarTypeVersionAsync(CarTypeVersionEntity t, List<CarPartsCarTypeVersionEntity> carPartsList)
        {
            try
            {
                sqlSugarClient.Ado.BeginTran();
                CarTypeVersionEntity model = sqlSugarClient.Insertable(t).ExecuteReturnEntity();
                if (model == null)
                {
                    sqlSugarClient.Ado.RollbackTran();//插入失败，数据回滚
                    return -1;
                }
                carPartsList.ForEach(a => a.CarTypeVersionId = model.Id);
                await sqlSugarClient.Insertable(carPartsList).ExecuteCommandAsync();
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                sqlSugarClient.Ado.RollbackTran();//数据回滚
                throw;
            }
        }

        public async Task<int> DeleteCarTypeVersionAsync(List<string> ids)
        {
            try
            {
                sqlSugarClient.Ado.BeginTran();
                await sqlSugarClient.Deleteable<CarTypeVersionEntity>().Where(it => ids.Contains(it.Id)).ExecuteCommandAsync();
                await sqlSugarClient.Deleteable<CarPartsCarTypeVersionEntity>().Where(it => ids.Contains(it.CarTypeVersionId)).ExecuteCommandAsync();
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                sqlSugarClient.Ado.RollbackTran();//数据回滚
                throw;
            }
        }

        public async Task<int> UpdatCarTypeVersionAsync(CarTypeVersionEntity t, List<CarPartsCarTypeVersionEntity> carPartsList)
        {
            try
            {
                sqlSugarClient.Ado.BeginTran();
                await sqlSugarClient.Updateable(t).ExecuteCommandAsync();
                await sqlSugarClient.Deleteable<CarPartsCarTypeVersionEntity>().Where(it => it.CarTypeVersionId == t.Id).ExecuteCommandAsync();
                await sqlSugarClient.Insertable(carPartsList).ExecuteCommandAsync();
                sqlSugarClient.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                sqlSugarClient.Ado.RollbackTran();//数据回滚
                throw;
            }
        }

        /// <summary>
        /// 获取所有列表
        /// </summary>
        /// <param name="where"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<List<RepCarTypeVersion>> GetListAsync(System.Linq.Expressions.Expression<Func<CarTypeVersionEntity, bool>> where = null, System.Linq.Expressions.Expression<Func<CarTypeVersionEntity, object>> order = null)
        {

            return await sqlSugarClient.Queryable<CarTypeVersionEntity>()
           .LeftJoin<BrandEntity>((m, b) => m.BrandId == b.Id)
          .LeftJoin<VehicleSeriesEntity>((m, b, v) => m.VehicleSeriesId == v.Id)
          .LeftJoin<CarTypeEntity>((m, b, v, c)=> m.CarTypeId == c.Id)
          .WhereIF(where != null, where)
          .OrderByIF(order != null, (m, b, v, c) => order).Select<RepCarTypeVersion>().ToListAsync();
        }

        /// <summary>
        /// 分页查询 加入条件 和 排序
        /// </summary>
        /// <param name="pageSize">每页显示多少条</param>
        /// <param name="current">当前第几页</param>
        /// <param name="where"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<PageModel<RepCarTypeVersion>> GetOrderPagesAsync(int pageSize, int current, System.Linq.Expressions.Expression<Func<CarTypeVersionEntity, bool>> where, System.Linq.Expressions.Expression<Func<CarTypeVersionEntity, object>> order = null, bool OrderByAsc = true)
        {

                RefAsync<int> totalCount = 0;//REF和OUT不支持异步,想要真的异步这是最优解
                OrderByType type = OrderByType.Asc;
                if (!OrderByAsc)
                    type = OrderByType.Desc;
                var list = await sqlSugarClient.Queryable<CarTypeVersionEntity>()
               .LeftJoin<BrandEntity>((m, b) => m.BrandId == b.Id)
              .LeftJoin<VehicleSeriesEntity>((m, b, v) => m.VehicleSeriesId == v.Id)
              .LeftJoin<CarTypeEntity>((m, b, v, c) => m.CarTypeId == c.Id)
              .WhereIF(where != null, where)
               .OrderByIF(order != null, order, type).Select<RepCarTypeVersion>().ToPageListAsync(current, pageSize, totalCount);
                return new PageModel<RepCarTypeVersion>() { Data = list, TotalCount = totalCount, TotalPage = (int)Math.Ceiling(totalCount / (double)pageSize) };
         }
    }
}
